package com.sinosoft.web.common.shiro.interceptors;

import com.sinosoft.hydra.um.domain.permission.SysUserMember;
import com.sinosoft.hydra.um.utils.AppUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;

/**
 * <p>session拦截<p>
 *
 * @author oujianlin@sinux.com.cn
 */
public class WebInterceptor implements HandlerInterceptor {

    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        SysUserMember sessionuser = AppUtils.getUser();
        String requestType = request.getHeader("X-Requested-With");// (获得extjs session过期值)
        if (StringUtils.isNotBlank(requestType) && requestType.toLowerCase().equals("xmlhttprequest")) {
            if (sessionuser == null || StringUtils.isBlank(sessionuser.getId())) {
                response.addHeader("_timeout", "true");
            }
        } else {
            if (sessionuser == null || StringUtils.isBlank(sessionuser.getId())) {
                PrintWriter out = response.getWriter();
                StringBuilder builder = new StringBuilder();
                builder.append("<script type=\"text/javascript\" charset=\"UTF-8\">");
                builder.append("window.top.location.href=\"");
                builder.append(request.getContextPath());
                builder.append("/pages/login.jsp\";</script>");
                out.print(builder.toString());
                out.close();
            }
        }
        return true;
    }

    public void postHandle(HttpServletRequest request,
                           HttpServletResponse response, Object handler,
                           ModelAndView modelAndView) throws Exception {

    }

    public void afterCompletion(HttpServletRequest request,
                                HttpServletResponse response, Object handler, Exception ex)
            throws Exception {
    }

}
